<template>
  <!-- 菜单查询 -->
  <el-row>
    <el-col :span="24">
      <el-card class="box-card" id="card">
        <div slot="header" class="clearfix">
          <span>菜单管理</span>
          <span>-您可以通过对菜单的信息进行编辑、删除等管理操作。^_^ <strong style="color:red;"> （注意：菜单操作的每次都会刷新页面）</strong> </span>
        </div>
        <el-row type="flex" class="row-bg operationButton" justify="start">
          <el-button type="primary" @click="addMenu" plain>添加</el-button>
        </el-row>
        <el-row>
          <el-col :span="15">
            <!-- 表单显示 -->
            <el-row
              type="flex"
              align="bottom"
              v-loading="loading"
              element-loading-text="拼命加载中"
              element-loading-background="rgb(255,255,255)"
            >
              <el-table
                :data="tableData"
                style="width: 100%;margin-bottom: 20px;"
                row-key="menuId"
                :default-expand-all="unfold"
                @row-click="selectRow"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren'
                }"
              >
                <el-table-column prop="menuText" label="菜单名称" sortable>
                </el-table-column>
                <el-table-column prop="menuUrl" label="菜单路由" sortable>
                </el-table-column>
                <el-table-column prop="menuIcon" label="菜单图标" sortable>
                  <template slot-scope="scope">
                    <i
                      style="margin-left: 50px; font-size: 20px;"
                      :class="scope.row.menuIcon"
                    ></i>
                  </template>
                </el-table-column>
                <el-table-column prop="menuPerms" label="权限标识" sortable>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="handleEdit(scope.$index, scope.row)"
                      >编辑</el-button
                    >
                    <template>
                      <el-popconfirm
                        title="确定要将该菜单删除吗？"
                        @confirm="handleDelete(scope.$index, scope.row)"
                      >
                        <el-button size="mini" type="danger" slot="reference"
                          >删除</el-button
                        >
                      </el-popconfirm>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-col>
          <el-col :span="8" :offset="1">
            <!-- 子菜单的菜单列表 -->
            <el-table :data="childData" style="width: 100%">
              <el-table-column label="名称">
                <template slot-scope="scope">
                  {{ scope.row.menuText }}
                </template>
              </el-table-column>
              <el-table-column label="路由">
                <template slot-scope="scope">
                  {{ scope.row.menuUrl }}
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    circle
                    @click="edit(scope.$index, scope.row)"
                  ></el-button>

                  <template>
                    <el-popconfirm
                      title="确定要将该菜单删除吗？"
                      @confirm="remove(scope.$index, scope.row)"
                    >
                      <el-button
                        size="mini"
                        type="danger"
                        icon="el-icon-delete"
                        slot="reference"
                        circle
                      ></el-button>
                    </el-popconfirm>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <!-- 对话框菜单 -->
        <el-dialog
          :title="iseditOrAdd"
          :visible.sync="dialogVisible"
          width="40%"
          :before-close="handleClose"
        >
          <!-- 数据 -->
          <el-form
            :model="menu"
            :rules="rules"
            ref="ruleForm"
            v-loading="childLoading"
            element-loading-text="拼命加载中"
            element-loading-background="rgb(255,255,255)"
          >
            <el-form-item
              label="菜单名称"
              prop="name"
              :label-width="formLabelWidth"
            >
              <el-input v-model="menu.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="菜单路由"
              prop="url"
              :label-width="formLabelWidth"
            >
              <el-input v-model="menu.url" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="菜单图标"
              prop="icon"
              :label-width="formLabelWidth"
            >
              <!-- <el-input v-model="menu.icon" autocomplete="off"></el-input> -->
              <el-select v-model="menu.icon" placeholder="请选择">
                <el-option
                  v-for="item in icons.length"
                  :key="item"
                  :label="icons[item]"
                  :value="icons[item]"
                >
                  <i :class="icons[item]"> {{ icons[item] }} </i>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="权限标识"
              prop="perms"
              :label-width="formLabelWidth"
            >
              <el-input v-model="menu.perms" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 级联选择器 -->
            <template v-if="iseditOrAdd == '新增菜单'">
              <div class="block">
                <span>选择级别：</span>
                <el-cascader
                  :options="options"
                  :props="{ checkStrictly: true }"
                  clearable
                  @change="handleChange"
                ></el-cascader>
              </div>
            </template>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-row>
              <el-col :span="7" :offset="9">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')"
                  >保 存</el-button
                >
              </el-col>
            </el-row>
          </span>
        </el-dialog>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      childData: [],
      loading: false,
      childLoading: false,
      unfold: false,
      dialogVisible: false,
      menu: {
        id: "",
        menuCode: "",
        name: "",
        url: "",
        icon: "",
        perms: "",
        parentCode: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入菜单名称", trigger: "blur" },
          { min: 2, max: 18, message: "长度在 2 到 18 个字符", trigger: "blur" }
        ],
        perms: [
          { required: true, message: "请输入权限标识名称", trigger: "blur" }
        ]
      },
      formLabelWidth: "83px",
      iseditOrAdd: "新增菜单",
      /**
       * 级联选择
       */
      options: [],
      /**
       * 图标库
       */
      icons: [
        "el-icon-delete-solid               ",
        "el-icon-delete                     ",
        "el-icon-s-tools                    ",
        "el-icon-setting                    ",
        "el-icon-user-solid                 ",
        "el-icon-user                       ",
        "el-icon-phone                      ",
        "el-icon-phone-outline              ",
        "el-icon-more                       ",
        "el-icon-more-outline               ",
        "el-icon-star-on                    ",
        "el-icon-star-off                   ",
        "el-icon-s-goods                    ",
        "el-icon-goods                      ",
        "el-icon-warning                    ",
        "el-icon-warning-outline            ",
        "el-icon-question                   ",
        "el-icon-info                       ",
        "el-icon-remove                     ",
        "el-icon-circle-plus                ",
        "el-icon-success                    ",
        "el-icon-error                      ",
        "el-icon-zoom-in                    ",
        "el-icon-zoom-out                   ",
        "el-icon-remove-outline             ",
        "el-icon-circle-plus-outline        ",
        "el-icon-circle-check               ",
        "el-icon-circle-close               ",
        "el-icon-s-help                     ",
        "el-icon-help                       ",
        "el-icon-minus                      ",
        "el-icon-plus                       ",
        "el-icon-check                      ",
        "el-icon-close                      ",
        "el-icon-picture                    ",
        "el-icon-picture-outline            ",
        "el-icon-picture-outline-round      ",
        "el-icon-upload                     ",
        "el-icon-upload2                    ",
        "el-icon-download                   ",
        "el-icon-camera-solid               ",
        "el-icon-camera                     ",
        "el-icon-video-camera-solid         ",
        "el-icon-video-camera               ",
        "el-icon-message-solid              ",
        "el-icon-bell                       ",
        "el-icon-s-cooperation              ",
        "el-icon-s-order                    ",
        "el-icon-s-platform                 ",
        "el-icon-s-fold                     ",
        "el-icon-s-unfold                   ",
        "el-icon-s-operation                ",
        "el-icon-s-promotion                ",
        "el-icon-s-home                     ",
        "el-icon-s-release                  ",
        "el-icon-s-ticket                   ",
        "el-icon-s-management               ",
        "el-icon-s-open                     ",
        "el-icon-s-shop                     ",
        "el-icon-s-marketing                ",
        "el-icon-s-flag                     ",
        "el-icon-s-comment                  ",
        "el-icon-s-finance                  ",
        "el-icon-s-claim                    ",
        "el-icon-s-custom                   ",
        "el-icon-s-opportunity              ",
        "el-icon-s-data                     ",
        "el-icon-s-check                    ",
        "el-icon-s-grid                     ",
        "el-icon-menu                       ",
        "el-icon-share                      ",
        "el-icon-d-caret                    ",
        "el-icon-caret-left                 ",
        "el-icon-caret-right                ",
        "el-icon-caret-bottom               ",
        "el-icon-caret-top                  ",
        "el-icon-bottom-left                ",
        "el-icon-bottom-right               ",
        "el-icon-back                       ",
        "el-icon-right                      ",
        "el-icon-bottom                     ",
        "el-icon-top                        ",
        "el-icon-top-left                   ",
        "el-icon-top-right                  ",
        "el-icon-arrow-left                 ",
        "el-icon-arrow-right                ",
        "el-icon-arrow-down                 ",
        "el-icon-arrow-up                   ",
        "el-icon-d-arrow-left               ",
        "el-icon-d-arrow-right              ",
        "el-icon-video-pause                ",
        "el-icon-video-play                 ",
        "el-icon-refresh                    ",
        "el-icon-refresh-right              ",
        "el-icon-refresh-left               ",
        "el-icon-finished                   ",
        "el-icon-sort                       ",
        "el-icon-sort-up                    ",
        "el-icon-sort-down                  ",
        "el-icon-rank                       ",
        "el-icon-loading                    ",
        "el-icon-view                       ",
        "el-icon-c-scale-to-original        ",
        "el-icon-date                       ",
        "el-icon-edit                       ",
        "el-icon-edit-outline               ",
        "el-icon-folder                     ",
        "el-icon-folder-opened              ",
        "el-icon-folder-add                 ",
        "el-icon-folder-remove              ",
        "el-icon-folder-delete              ",
        "el-icon-folder-checked             ",
        "el-icon-tickets                    ",
        "el-icon-document-remove            ",
        "el-icon-document-delete            ",
        "el-icon-document-copy              ",
        "el-icon-document-checked           ",
        "el-icon-document                   ",
        "el-icon-document-add               ",
        "el-icon-printer                    ",
        "el-icon-paperclip                  ",
        "el-icon-takeaway-box               ",
        "el-icon-search                     ",
        "el-icon-monitor                    ",
        "el-icon-attract                    ",
        "el-icon-mobile                     ",
        "el-icon-scissors                   ",
        "el-icon-umbrella                   ",
        "el-icon-headset                    ",
        "el-icon-brush                      ",
        "el-icon-mouse                      ",
        "el-icon-coordinate                 ",
        "el-icon-magic-stick                ",
        "el-icon-reading                    ",
        "el-icon-data-line                  ",
        "el-icon-data-board                 ",
        "el-icon-pie-chart                  ",
        "el-icon-data-analysis              ",
        "el-icon-collection-tag             ",
        "el-icon-film                       ",
        "el-icon-suitcase                   ",
        "el-icon-suitcase-1                 ",
        "el-icon-receiving                  ",
        "el-icon-collection                 ",
        "el-icon-files                      ",
        "el-icon-notebook-1                 ",
        "el-icon-notebook-2                 ",
        "el-icon-toilet-paper               ",
        "el-icon-office-building            ",
        "el-icon-school                     ",
        "el-icon-table-lamp                 ",
        "el-icon-house                      ",
        "el-icon-no-smoking                 ",
        "el-icon-smoking                    ",
        "el-icon-shopping-cart-full         ",
        "el-icon-shopping-cart-1            ",
        "el-icon-shopping-cart-2            ",
        "el-icon-shopping-bag-1             ",
        "el-icon-shopping-bag-2             ",
        "el-icon-sold-out                   ",
        "el-icon-sell                       ",
        "el-icon-present                    ",
        "el-icon-box                        ",
        "el-icon-bank-card                  ",
        "el-icon-money                      ",
        "el-icon-coin                       ",
        "el-icon-wallet                     ",
        "el-icon-discount                   ",
        "el-icon-price-tag                  ",
        "el-icon-news                       ",
        "el-icon-guide                      ",
        "el-icon-male                       ",
        "el-icon-female                     ",
        "el-icon-thumb                      ",
        "el-icon-cpu                        ",
        "el-icon-link                       ",
        "el-icon-connection                 ",
        "el-icon-open                       ",
        "el-icon-turn-off                   ",
        "el-icon-set-up                     ",
        "el-icon-chat-round                 ",
        "el-icon-chat-line-round            ",
        "el-icon-chat-square                ",
        "el-icon-chat-dot-round             ",
        "el-icon-chat-dot-square            ",
        "el-icon-chat-line-square           ",
        "el-icon-message                    ",
        "el-icon-postcard                   ",
        "el-icon-position                   ",
        "el-icon-turn-off-microphone        ",
        "el-icon-microphone                 ",
        "el-icon-close-notification         ",
        "el-icon-bangzhu                    ",
        "el-icon-time                       ",
        "el-icon-odometer                   ",
        "el-icon-crop                       ",
        "el-icon-aim                        ",
        "el-icon-switch-button              ",
        "el-icon-full-screen                ",
        "el-icon-copy-document              ",
        "el-icon-mic                        ",
        "el-icon-stopwatch                  ",
        "el-icon-medal-1                    ",
        "el-icon-medal                      ",
        "el-icon-trophy                     ",
        "el-icon-trophy-1                   ",
        "el-icon-first-aid-kit              ",
        "el-icon-discover                   ",
        "el-icon-place                      ",
        "el-icon-location                   ",
        "el-icon-location-outline           ",
        "el-icon-location-information       ",
        "el-icon-add-location               ",
        "el-icon-delete-location            ",
        "el-icon-map-location               ",
        "el-icon-alarm-clock                ",
        "el-icon-timer                      ",
        "el-icon-watch-1                    ",
        "el-icon-watch                      ",
        "el-icon-lock                       ",
        "el-icon-unlock                     ",
        "el-icon-key                        ",
        "el-icon-service                    ",
        "el-icon-mobile-phone               ",
        "el-icon-bicycle                    ",
        "el-icon-truck                      ",
        "el-icon-ship                       ",
        "el-icon-basketball                 ",
        "el-icon-football                   ",
        "el-icon-soccer                     ",
        "el-icon-baseball                   ",
        "el-icon-wind-power                 ",
        "el-icon-light-rain                 ",
        "el-icon-lightning                  ",
        "el-icon-heavy-rain                 ",
        "el-icon-sunrise                    ",
        "el-icon-sunrise-1                  ",
        "el-icon-sunset                     ",
        "el-icon-sunny                      ",
        "el-icon-cloudy                     ",
        "el-icon-partly-cloudy              ",
        "el-icon-cloudy-and-sunny           ",
        "el-icon-moon                       ",
        "el-icon-moon-night                 ",
        "el-icon-dish                       ",
        "el-icon-dish-1                     ",
        "el-icon-food                       ",
        "el-icon-chicken                    ",
        "el-icon-fork-spoon                 ",
        "el-icon-knife-fork                 ",
        "el-icon-burger                     ",
        "el-icon-tableware                  ",
        "el-icon-sugar                      ",
        "el-icon-dessert                    ",
        "el-icon-ice-cream                  ",
        "el-icon-hot-water                  ",
        "el-icon-water-cup                  ",
        "el-icon-coffee-cup                 ",
        "el-icon-cold-drink                 ",
        "el-icon-goblet                     ",
        "el-icon-goblet-full                ",
        "el-icon-goblet-square              ",
        "el-icon-goblet-square-full         ",
        "el-icon-refrigerator               ",
        "el-icon-grape                      ",
        "el-icon-watermelon                 ",
        "el-icon-cherry                     ",
        "el-icon-apple                      ",
        "el-icon-pear                       ",
        "el-icon-orange                     ",
        "el-icon-coffee                     ",
        "el-icon-ice-tea                    ",
        "el-icon-ice-drink                  ",
        "el-icon-milk-tea                   ",
        "el-icon-potato-strips              ",
        "el-icon-lollipop                   ",
        "el-icon-ice-cream-square           ",
        "el-icon-ice-cream-round            "
      ]
    };
  },
  methods: {
    /**
     * 编辑按钮
     */
    handleEdit(index, row) {
      this.menu.id = row.menuId;
      this.menu.menuCode = row.menuCode;
      this.menu.name = row.menuText;
      this.menu.url = row.menuUrl;
      this.menu.icon = row.menuIcon;
      this.menu.perms = row.menuPerms;
      this.menu.parentCode = row.menuParentCode;
      this.iseditOrAdd = "修改菜单";
      this.dialogVisible = true;
    },

    /**
     * 删除按钮
     */
    handleDelete(index, row) {
      let id = row.menuId;
      this.$axios
        .get("/api/biz/menu/del/" + id)
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            let array = this.$store.state.userStore.rights;
            for (let i = 0; i < array.length; i++) {
              if (array[i].menuId == id) {
                array.splice(i, 1);
                break;
              }
            }
            this.$store.commit("update", array);
            this.$message.success("删除成功");
            location.reload();
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    /**
     * 子菜单编辑按钮
     */
    edit(index, row) {
      this.handleEdit(index, row);
    },
    /**
     * 子菜单删除按钮
     */
    remove(index, row) {
      this.handleDelete(index, row);
    },
    /**
     * 显示子菜单的菜单
     */
    selectRow(row, column, event) {
      let menu = this.$store.state.userStore.rights.filter(
        right => right.menuParentCode == row.menuCode
      );
      this.childData = menu;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    /**
     * 提交
     */
    submitForm(formName) {
      if (this.iseditOrAdd == "修改菜单") {
        this.modifySubmit(formName);
      } else {
        this.addSubmit(formName);
      }
    },
    /**
     * 修改提交
     */
    modifySubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.childLoading = true;
          let submitData = {
            menuId: this.menu.id,
            menuCode: this.menu.menuCode,
            menuPerms: this.menu.perms,
            menuText: this.menu.name,
            menuUrl: this.menu.url,
            menuIcon: this.menu.icon,
            menuParentCode: this.menu.parentCode
          };
          this.$axios
            .post("/api/biz/menu/modify", submitData)
            .then(result => {
              let data = result.data;
              if (data.code == 0) {
                this.childLoading = false;
                this.$message.success("修改成功");
                let menuData = this.$store.state.userStore.rights;
                for (const key in menuData) {
                  if (menuData[key].menuId == this.menu.id) {
                    menuData.splice(key, 1, submitData);
                    this.$store.commit("update", menuData);
                    break;
                  }
                }
                this.dialogVisible = false;
                location.reload();
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //TODO: menuCode 待完成
    /**
     * 新增提交
     */
    addSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.menu.parentCode == "") {
            this.menu.parentCode = "ROOT_MENU";
          }

          let submitData = {
            menuId: this.menu.id,
            menuCode: this.menu.menuCode,
            menuPerms: this.menu.perms,
            menuText: this.menu.name,
            menuUrl: this.menu.url,
            menuIcon: this.menu.icon,
            menuParentCode: this.menu.parentCode
          };
          console.log(submitData);
          this.childLoading = true;
          this.$axios
            .post("/api/biz/menu/add", submitData)
            .then(result => {
              let data = result.data;
              if (data.code == 0) {
                this.childLoading = false;
                this.$message.success("新增成功");
                //TODO: menuCode 待完成

                let newMenu = data.data;
                console.log(newMenu);
                // let menuData = this.$store.state.userStore.rights;
                // for (const key in menuData) {
                //   if (menuData[key].menuId == this.menu.id) {
                //     menuData.splice(key, 1, submitData);
                //     this.$store.commit("update", menuData);
                //     break;
                //   }
                // }
                this.dialogVisible = false;
                location.reload();
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /**
     * 清除
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /**
     * 添加菜单
     */
    addMenu() {
      this.iseditOrAdd = "新增菜单";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["ruleForm"].resetFields();
      });
    },
    /**
     * 添加菜单-子菜单路径
     */
    handleChange(value) {
      this.menu.parentCode = this.$store.state.userStore.rights[
        value.length
      ].menuParentCode;
      console.log(value);
    }
  },
  mounted() {
    let menus = this.$store.state.userStore.rights;
    //列表
    let parentArray = [];
    let childArray = [];

    //新增选择菜单
    let optionsArray = [];
    for (const parent in menus) {
      if (menus[parent].menuParentCode == "ROOT_MENU") {
        childArray = [];

        let optionsArray1 = [];
        for (const child in menus) {
          if (menus[child].menuParentCode == menus[parent].menuCode) {
            childArray.push(menus[child]);

            let optionsArray2 = [];
            for (const final in menus) {
              if (menus[final].menuParentCode == menus[child].menuCode) {
                optionsArray2.push({
                  value: menus[final].menuId,
                  label: menus[final].menuText,
                  disabled: true
                });
              }
            }
            optionsArray1.push({
              value: menus[child].menuId,
              label: menus[child].menuText,
              children: optionsArray2
            });
          }
        }
        parentArray.push({
          menuId: menus[parent].menuId,
          menuCode: menus[parent].menuCode,
          menuIcon: menus[parent].menuIcon,
          menuParentCode: menus[parent].menuParentCode,
          menuPerms: menus[parent].menuPerms,
          menuText: menus[parent].menuText,
          menuUrl: menus[parent].menuUrl,
          children: childArray
        });

        optionsArray.push({
          value: menus[parent].menuId,
          label: menus[parent].menuText,
          children: optionsArray1
        });
      }
    }
    this.tableData = parentArray;

    this.options = optionsArray;
  }
};
</script>

<style scoped>
#card {
  width: 100%;
  margin: 0px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
  border-bottom: 1px solid #ebeef5;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.clearfix {
  text-align: left;
}
.clearfix > span:last-child {
  color: #333333;
  font-size: 13px;
}
.clearfix > span:first-child {
  font-weight: bold;
  color: #59a6f5;
  margin-right: 20px;
}
.queryButton {
  padding-bottom: 20px;
}
.pagination {
  padding-top: 20px;
}

.el-form-item__content {
  margin-left: 100px;
  margin-right: 50px;
}
.el-select {
  width: 100%;
}
.el-dialog__body {
  padding-top: 10px;
}
.delButton {
  margin: 10px 50px;
}
.operationButton {
  margin-bottom: 10px;
}
.el-cascader {
  width: 480px;
}
</style>
